package tletlis.UI;


import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.io.*;

/**
 *
 * @author OLBZINATOR^^^MTHfCKr
 *
 * Highscore contains a list with the top ten players of tletlis.
 *
 * The highscore is only avalible in singleplayer.
 */
public class Highscore extends JFrame {
    java.util.List<String> hsList = new ArrayList<String>();


    /**
     *
     * @param playerName is the name to be seen on the highscore
     * @param score is the score the player got during the game
     * @throws java.io.FileNotFoundException
     * @throws java.io.IOException
     */
    public Highscore(String playerName, int score) throws FileNotFoundException, IOException{

    setHighScore(playerName,score);
    setLayout(new GridLayout(10,1));
    paintNewHighScore();
    this.setTitle("Tletlis © Highscore");

    for(int i=0;i<10;i++){
        JLabel hsLabel = new JLabel();
        hsLabel.setText(i+1 +". " +hsList.get(i));
        add(hsLabel);
    }

    setPreferredSize(new Dimension(300,400));
    setVisible(true);
    pack();
    

    }


    private void paintNewHighScore( ) throws IOException{

                PrintWriter outPrint = new PrintWriter(new BufferedWriter(new
                FileWriter("Highscore.txt")));
                for(int i = 0; i < 10; i++){
                    outPrint.println(hsList.get(i));
                }
                outPrint.close();
    }

    /**
     * setHighScore will see if the the last score was one of the ten best
     * scores through the history of tletlis. If they pass the test, they will
     * be added to the highscore and be saved to Highscore.txt!
     *
     * @param name is the name to be proven worthy.
     * @param score is the score to be proven worthy.
     * @throws java.io.FileNotFoundException
     * @throws java.io.IOException
     */
    public void setHighScore(String name, int score)
            throws FileNotFoundException, IOException{

        
        
        Scanner sc = new Scanner(new File("Highscore.txt"));
           
        String prevName = sc.next();
        int prevScore = sc.nextInt();

        while(sc.hasNext()){

             if (score > prevScore){

                String tempName = prevName;
                int tempScore = prevScore;

                prevScore = score;
                prevName = name;

                name = tempName;
                score = tempScore;
               
             }
              else{
                 hsList.add(prevName + " " +prevScore);
                 sc.nextLine();
                 prevName = sc.next();
                 prevScore = sc.nextInt();
                 
             }

 
            
        }
        hsList.add(prevName + " " +prevScore);
        
    }
}
